package com.demo.springboot;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * BeanPostProcessor 会在每个Bean初始化的时候，调用一次这两个方法。
 * 两个方法不能返回null，否则容器找不到(5.1 无此问题)
 */
@Component
public class EchoBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 是在Bean依赖装配（属性设置）完成之后触发
     * 这里可以对指定的对象做一些处理，比如说返回该对象的代理对象
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("-----postProcessBeforeInitialization-----" + beanName);
        if(bean instanceof MySpringContextAware){
            MySpringContextAware msca = (MySpringContextAware)bean;
            msca.setApplicationContext(applicationContext);
        }
        return bean;
    }

    /**
     * 是在Bean 初始化（init）之后执行的
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("-----postProcessAfterInitialization----" + beanName);
        return bean;
    }
}
